import {ScrollView, Text, View} from "@tarojs/components";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {getOrderStatusStyle, OrderStatus, OrderStatusInfoType} from "@/common/enums";
import {Button, Cell, CellGroup, Empty, Image} from "@antmjs/vantui";
import DateUtils from "@/utils/date_utils";
import Utils from "@/utils/common";
import {IdParams, OrderItem} from "@/common/apis/model";
import {
  orderCancelApi,
  orderInfoApi,
} from "@/common/apis/home_datasource";
import ShowUtils from "@/utils/show_utils";
import LocalData from "@/common/local_data";
import Taro from "@tarojs/taro";
import NumberUtils from "@/utils/number_utils";
import RouthPath from "@/common/RouthPath";
import LogUtils from "@/utils/log";
import './order_detail.less'
import AssetImage from "@/common/AssetImage";


definePageConfig({
  navigationBarTitleText: '预约详情'
})
export default function Order_detail() {
  const statusStyle = useRef<OrderStatusInfoType>();
  const orderInfo = useRef<OrderItem>();
  const idParams = useRef<IdParams>();
  const channelEvent = useRef<Taro.EventChannel | null>();

  const getOrderInfo = useCallback(() => {
    if (idParams.current && idParams.current?.id) {
      orderInfoApi(idParams.current?.id).then((res) => {
        if (res) {
          orderInfo.current = res;
          statusStyle.current = getOrderStatusStyle(res.status)
          setRefresh({})
        }
      })
    }
  }, []);

  const [, setRefresh] = useState({})
  useEffect(() => {
    const i = Utils.getI()
    const params = Utils.getParamsByRouter(i)
    channelEvent.current = Utils.getChannel(i)
    if (params && params.data) {
      idParams.current = Utils.getObjectWithUrl<IdParams>(params.data)
      getOrderInfo();
    }
  }, [getOrderInfo]);

  const handleButtons = useCallback((type) => {
    if (orderInfo.current) {
      if (type === 2) {
        Utils.modal("提示", "确定要取消吗？", true, (ok) => {
          if (ok) {
            orderCancelApi(orderInfo.current?.id).then((r) => {
              if (r) {
                Utils.showOkToast("取消成功")
                getOrderInfo()
              }
            })
          }
        })
      } else if (type === 4) {
        const params: IdParams = {
          id: orderInfo.current?.reports ?? ''
        }
        LogUtils.info(params)
        Utils.navigateTo(
          {
            url: Utils.getUrlWithObject(RouthPath.testResult, params),
          }
        )
      }
    }
  }, [getOrderInfo]);

  const getWayOrRecycleText = useCallback((id, type) => {
    if (id == null || type == null) {
      return '';
    }
    if (type === 0) {
      return LocalData.way[id].text
    } else if (type === 1) {
      return LocalData.recycle[id].text
    } else {
      return LocalData.way2[id].text
    }
  }, []);
  const renderBottomButtons = useCallback(() => {
    let bottomButtons;
    //如果已完成
    if (orderInfo.current?.status === OrderStatus.FINISHED) {
      bottomButtons = (
        <View style={{display: 'flex', flexDirection: 'row',}}>
          {
            orderInfo.current?.reports ?
              <Button style={{flex: 1, margin: '24px'}} size='normal' type='info' onClick={(e) => {
                handleButtons(4);
              }}
              >
                查看检测结果
              </Button> : null
          }
        </View>
      )
    } else {
      bottomButtons = (
        <View style={{display: 'flex', flexDirection: 'row',}}>
          <Button style={{flex: 1, margin: '24px'}} size='normal' type='info' hairline plain onClick={(e) => {
            handleButtons(2);
          }}
          >
            取消
          </Button>
        </View>
      )
    }

    return (
      <View>
        {bottomButtons}
      </View>
    )
  }, []);


  const renderTimeOrNum = useCallback(() => {
    const machineType = orderInfo.current?.machineType;
    if (machineType === LocalData.notTimeId) {
      return (
        <Cell renderIcon='样品数量' renderTitle={<Text
          className='titleStyle'
          style={{
            color: 'black',
            display: 'inline-block',
            width: '100%',
            marginLeft: '10px'
          }}
        >{orderInfo.current?.bookTotalTime}</Text>}
        />
      )
    } else {
      return (
        <View>
          <Cell renderIcon={`预约时间(${DateUtils.getHours(orderInfo.current?.bookAllTimes)}h)`}/>
          <View className='gridLayout100_2'>
            {
              DateUtils.formatAndMergeDateTimeRanges(orderInfo.current?.bookAllTimes).map((time, index) => {
                return (
                  <View key={index} className='gridItem'>
                    <Text>{time.date}</Text>
                    <Text>{time.time}</Text>
                  </View>
                )
              })
            }
          </View>
        </View>
      )
    }
  }, []);


  return (
    <View>
      {
        orderInfo.current ?
          <View style={{height: '100vh', boxSizing: 'border-box', display: 'flex', flexDirection: 'column'}}>
            <View style={{boxSizing: 'border-box', flex: 1, position: 'relative', overflow: 'hidden'}}>
              <ScrollView scrollY
                          style={{boxSizing: 'border-box', height: '100%'}}
              >
                <View>
                  <Cell
                    renderTitle={<View
                      style={{display: 'flex', justifyContent: 'space-between'}}
                    ><View><Text>订单号</Text><Text
                      style={{color: 'black'}}
                    >{`(${orderInfo.current?.id})`}</Text></View>{
                      statusStyle.current ? <Text
                        style={{color: statusStyle.current?.color}}
                      >{statusStyle.current?.text}</Text> : <View></View>
                    }</View>}
                  />
                  <CellGroup
                    title='项目信息'
                  >
                    <Cell renderIcon='机器'
                          renderTitle={<Text
                            className='titleStyle'
                            style={{
                              color: 'black',
                              display: 'inline-block',
                              width: '100%',
                              marginLeft: '10px'
                            }}
                          >{orderInfo.current?.machineName}</Text>}
                    />
                    <Cell renderIcon='项目'
                          renderTitle={<View style={{display: 'flex', alignItems: 'center', flexDirection: 'row'}}>
                            <View style={{marginLeft: '10px'}}>
                              <Image src={ShowUtils.getDefault(orderInfo.current?.projectImage, '')}
                                     style={{width: '50px', height: '50px'}} fit='cover'
                              />
                            </View>
                            <Text
                              className='titleStyle'
                              style={{
                                color: 'black',
                                display: 'inline-block',
                                width: '100%',
                                marginLeft: '20px'
                              }}
                            >{orderInfo.current?.projectName}</Text></View>}
                    />
                    {
                      renderTimeOrNum()
                    }
                    <Cell renderIcon='价格'
                          renderTitle={<View style={{
                            marginLeft: '10px',
                            flex: 1,
                            display: 'flex',
                            flexDirection: 'row',
                            justifyContent: 'flex-start',
                            alignItems: 'center'
                          }}
                          >
                            <Text style={{
                              fontSize: '16px',
                              color: 'red',
                            }}
                            >{ShowUtils.getDefaultPrice(orderInfo.current?.actualAmount)}</Text>
                            <Text style={{
                              fontSize: '14px',
                              color: 'gray',
                              textDecoration: 'line-through',
                            }}
                            >{`(${ShowUtils.getDefaultPrice(orderInfo.current?.amount)})`}</Text>
                          </View>}
                    />
                  </CellGroup>
                  <CellGroup title={<Text>用户信息</Text>}>
                    <Cell renderIcon='联系人姓名' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{orderInfo.current?.contacts}</Text>}
                    />
                    <Cell renderIcon='联系人电话' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{orderInfo.current?.phone}</Text>}
                    />
                    {
                      ShowUtils.isValidTeamId(orderInfo.current?.teamId) ?
                        <Cell renderIcon='团队名称' renderTitle={<Text
                          className='titleStyle'
                          style={{
                            color: 'black',
                            display: 'inline-block',
                            width: '100%',
                            marginLeft: '20px'
                          }}
                        >{orderInfo.current?.teamName}</Text>}
                        /> : null
                    }
                  </CellGroup>

                  <CellGroup title='样品信息'>

                    <Cell renderIcon='拍摄方式' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.shootingWay, 2)
                    }</Text>}
                    />

                    <Cell renderIcon='取样方式' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.way, 0)
                    }</Text>}
                    />
                    {
                      orderInfo.current?.way === 1 ? <Cell renderIcon='邮寄地址' renderTitle={<Text
                        className='titleStyle'
                        style={{
                          color: 'black',
                          display: 'inline-block',
                          marginRight: '20px',
                          marginLeft: '20px'
                        }}
                      >{LocalData.acceptAddress}</Text>}
                                                           renderExtra={<Image src={AssetImage.copy as string} style={{
                                                             width: '24px',
                                                             height: '24px'
                                                           }}
                                                           />}
                                                           onClick={() => {
                                                             Utils.copyToClipboard()
                                                           }}
                      /> : null
                    }

                    <Cell renderIcon='样品是否回收' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        marginLeft: '20px'
                      }}
                    >{
                      getWayOrRecycleText(orderInfo.current?.recycle, 1)
                    }</Text>}
                    />
                    {
                      orderInfo.current?.recycle === 0 ? <Cell renderIcon='回收地址' renderTitle={<Text
                        className='titleStyle'
                        style={{
                          color: 'black',
                          display: 'inline-block',
                          marginRight: '20px',
                          marginLeft: '20px'
                        }}
                      >{orderInfo.current?.recycleDetail}</Text>}
                      /> : null
                    }
                    <Cell renderIcon='备注' renderTitle={<Text
                      className='titleStyle'
                      style={{
                        color: 'black',
                        display: 'inline-block',
                        width: '100%',
                        boxSizing: 'border-box',
                        paddingLeft: '20px',
                        paddingRight: '10px',
                      }}
                    >{ShowUtils.getDefault(orderInfo.current?.note, '无')}</Text>}
                    />
                  </CellGroup>
                  {
                    NumberUtils.isActuallyNumber(orderInfo.current?.payWay) && orderInfo.current?.status === OrderStatus.FINISHED ?
                      <Cell renderIcon={<Text style={{marginRight: '10px'}}>支付方式</Text>}
                            title={ShowUtils.getPayWay(orderInfo.current?.payWay)}
                      /> : null
                  }
                </View>
              </ScrollView>
            </View>
            {
              renderBottomButtons()
            }
          </View> : <View>
            <Empty description='暂无数据'/>
          </View>
      }
    </View>
  )
}
